'use client';

import { use, useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { fetchApi, getDateTime } from '@/lib/utils/client';
import Loading from '@/app/component/Loading';
import NavTabs from '../../navTabs';
import {
	ORDER_STATUS_LABEL,
	SHIPMENT_STATUS_LABEL,
	REFUND_REASON_LABEL,
	REFUND_TYPE_LABEL,
	REFUND_STATUS_LABEL,
	type OrderDetail,
	type RefundReasonType,
	type RefundType
} from '@/types/store';

const REASON_OPTIONS: { value: RefundReasonType; label: string }[] = [
	{ value: 1, label: REFUND_REASON_LABEL[1] },
	{ value: 2, label: REFUND_REASON_LABEL[2] },
	{ value: 3, label: REFUND_REASON_LABEL[3] },
	{ value: 4, label: REFUND_REASON_LABEL[4] },
	{ value: 5, label: REFUND_REASON_LABEL[5] },
	{ value: 6, label: REFUND_REASON_LABEL[6] },
	{ value: 7, label: REFUND_REASON_LABEL[7] }
];

export default function OrderDetailPage({ params }: { params: Promise<{ id: string }> })
{
	const { id } = use(params);
	const orderID = parseInt(id, 10);
	const router = useRouter();

	const [order, setOrder] = useState<OrderDetail|null>(null);
	const [loading, setLoading] = useState(true);
	const [error, setError] = useState<string|null>(null);

	const [refundOpen, setRefundOpen] = useState<RefundType|null>(null);
	const [reasonType, setReasonType] = useState<RefundReasonType>(1);
	const [reasonMemo, setReasonMemo] = useState('');
	const [submitting, setSubmitting] = useState(false);

	const load = useCallback(async () => {
		setLoading(true);
		const res = await fetchApi<OrderDetail>(`/api/store/orders/${orderID}`, { silent: true });

		if (res.success && res.data) {
			setOrder(res.data);
			setError(null);
		}
		else {
			setError(res.message || '주문을 불러올 수 없습니다.');
		}

		setLoading(false);
	}, [orderID]);

	useEffect(() => {
		load();
	}, [load]);

	const openModal = (type: RefundType) => {
		setRefundOpen(type);
		setReasonType(type === 3 ? 2 : 1);
		setReasonMemo('');
	};

	const closeModal = () => {
		setRefundOpen(null);
		setReasonMemo('');
	};

	const handleSubmit = async () => {
		if (refundOpen === null) {
			return;
		}

		if (reasonType === 7 && !reasonMemo.trim()) {
			alert('사유가 "기타"인 경우 상세 사유를 입력해 주세요.');
			return;
		}

		setSubmitting(true);

		const res = await fetchApi(`/api/store/orders/${orderID}/refunds`, {
			method: 'POST',
			body: {
				type: refundOpen,
				reasonType,
				reasonMemo: reasonMemo.trim() || null
			},
			silent: true
		});

		setSubmitting(false);

		if (res.success) {
			alert('환불 요청이 접수되었습니다. 관리자 검토 후 처리됩니다.');
			closeModal();
			load();
		}
		else {
			alert(res.message || '환불 요청에 실패했습니다.');
		}
	};

	if (loading) {
		return (
			<>
				<NavTabs />
				<Loading />
			</>
		);
	}

	if (error || !order) {
		return (
			<>
				<NavTabs />
				<div className="container mx-auto px-4 py-12 text-center">
					<p className="text-red-600 mb-4">{error || '주문을 찾을 수 없습니다.'}</p>
					<Link href="/orders" className="text-blue-600 underline">주문 내역으로</Link>
				</div>
			</>
		);
	}

	const canCancel = order.status === 2 || order.status === 3;
	const canReturnExchange = order.status === 5;
	const hasPending = order.refunds.some(r => r.status === 1);

	const subtotal = order.items.reduce((acc, it) => acc + it.unitPrice * it.quantity, 0);
	const shippingFee = order.shipment?.shippingFee ?? 0;

	return (
		<>
			<NavTabs />

			<div className="container mx-auto px-4 py-6 max-w-2xl">
				<div className="mb-4 flex items-center justify-between">
					<button type="button" onClick={() => router.push('/orders')} className="text-sm text-blue-600 hover:underline">
						← 주문 내역
					</button>
					<button type="button" onClick={() => window.print()} className="text-xs text-neutral-500 hover:text-neutral-700">
						인쇄
					</button>
				</div>

				{/* 영수증 카드 */}
				<div className="bg-white dark:bg-neutral-900 border border-neutral-300 dark:border-neutral-700 rounded-lg p-6 shadow-sm">
					{/* 헤더 */}
					<div className="text-center border-b border-dashed border-neutral-300 dark:border-neutral-700 pb-4 mb-4">
						<div className="text-xs tracking-widest text-neutral-500 uppercase">Order Receipt</div>
						<div className="font-mono text-lg font-bold mt-1">{order.orderNumber}</div>
						<div className="text-xs text-neutral-500 mt-1">{getDateTime(order.createdAt)}</div>
						<div className="mt-2">
							<span className="inline-block px-3 py-1 rounded-full text-xs font-semibold bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300">
								{ORDER_STATUS_LABEL[order.status]}
							</span>
						</div>
					</div>

					{/* 주문자/채널 메타 */}
					<dl className="text-xs space-y-1 mb-4">
						{order.paidAt && (
							<div className="flex justify-between"><dt className="text-neutral-500">결제 일시</dt><dd>{getDateTime(order.paidAt)}</dd></div>
						)}
						{order.channelName && (
							<div className="flex justify-between"><dt className="text-neutral-500">후원 채널</dt><dd>{order.channelName}</dd></div>
						)}
					</dl>

					{/* 아이템 */}
					<div className="border-t border-neutral-200 dark:border-neutral-800 pt-3">
						<table className="w-full text-sm">
							<thead>
								<tr className="text-xs text-neutral-500 border-b border-neutral-200 dark:border-neutral-800">
									<th className="text-left py-1 font-normal">상품</th>
									<th className="text-right py-1 font-normal w-12">수량</th>
									<th className="text-right py-1 font-normal w-24">소계</th>
								</tr>
							</thead>
							<tbody>
								{order.items.map((item) => (
									<tr key={item.id} className="border-b border-neutral-100 dark:border-neutral-800/60 last:border-0">
										<td className="py-2 align-top">
											<div className="flex items-start gap-2">
												<div className="w-10 h-10 bg-neutral-100 dark:bg-neutral-800 rounded overflow-hidden flex-shrink-0">
													{item.productThumbnail ? (
														// eslint-disable-next-line @next/next/no-img-element
														<img src={item.productThumbnail} alt="" className="w-full h-full object-cover" />
													) : null}
												</div>
												<div className="min-w-0">
													<div className="font-medium truncate">{item.productName}</div>
													<div className="text-xs text-neutral-500">
														{item.type === 1 ? '실물' : '쿠폰'} · {item.unitPrice.toLocaleString()}P
													</div>
													{item.type === 2 && item.issuedCouponCodeID !== null && (
														<Link href="/inventory" className="text-xs text-blue-600 hover:underline">보관함에서 확인 →</Link>
													)}
												</div>
											</div>
										</td>
										<td className="py-2 text-right align-top tabular-nums">{item.quantity}</td>
										<td className="py-2 text-right align-top tabular-nums">{(item.unitPrice * item.quantity).toLocaleString()}P</td>
									</tr>
								))}
							</tbody>
						</table>
					</div>

					{/* 합계 */}
					<div className="border-t border-neutral-200 dark:border-neutral-800 mt-3 pt-3 text-sm space-y-1">
						<div className="flex justify-between text-neutral-600 dark:text-neutral-400">
							<span>상품 금액</span>
							<span className="tabular-nums">{subtotal.toLocaleString()}P</span>
						</div>
						{shippingFee > 0 && (
							<div className="flex justify-between text-neutral-600 dark:text-neutral-400">
								<span>배송비</span>
								<span className="tabular-nums">{shippingFee.toLocaleString()}P</span>
							</div>
						)}
						<div className="flex justify-between items-baseline pt-2 mt-1 border-t border-dashed border-neutral-300 dark:border-neutral-700">
							<span className="text-base font-bold">총 결제 금액</span>
							<span className="text-xl font-extrabold text-red-600 dark:text-red-400 tabular-nums">{order.totalAmount.toLocaleString()}P</span>
						</div>
					</div>

					{/* 배송 정보 */}
					{order.shipment && (
						<div className="border-t border-neutral-200 dark:border-neutral-800 mt-4 pt-3 text-xs space-y-1">
							<div className="font-semibold mb-1">배송 정보</div>
							<div className="flex justify-between"><span className="text-neutral-500">상태</span><span>{SHIPMENT_STATUS_LABEL[order.shipment.status]}</span></div>
							<div className="flex justify-between"><span className="text-neutral-500">택배사</span><span>{order.shipment.carrier || '-'}</span></div>
							<div className="flex justify-between"><span className="text-neutral-500">송장번호</span><span className="font-mono">{order.shipment.trackingNumber || '-'}</span></div>
							{order.shipment.shippedAt && (
								<div className="flex justify-between"><span className="text-neutral-500">출고</span><span>{getDateTime(order.shipment.shippedAt)}</span></div>
							)}
							{order.shipment.deliveredAt && (
								<div className="flex justify-between"><span className="text-neutral-500">배송 완료</span><span>{getDateTime(order.shipment.deliveredAt)}</span></div>
							)}
						</div>
					)}

					{/* 환불 요청 이력 */}
					{order.refunds.length > 0 && (
						<div className="border-t border-neutral-200 dark:border-neutral-800 mt-4 pt-3 text-xs space-y-2">
							<div className="font-semibold">환불 요청 이력</div>
							{order.refunds.map((r) => (
								<div key={r.id} className="border border-neutral-200 dark:border-neutral-800 rounded p-2">
									<div className="flex justify-between items-center mb-1">
										<span className="font-semibold">{REFUND_TYPE_LABEL[r.type]} · {REFUND_REASON_LABEL[r.reasonType]}</span>
										<span className="px-1.5 py-0.5 rounded text-[10px] font-semibold bg-neutral-100 text-neutral-700 dark:bg-neutral-800 dark:text-neutral-300">
											{REFUND_STATUS_LABEL[r.status]}
										</span>
									</div>
									{r.reason && r.reason !== REFUND_REASON_LABEL[r.reasonType] && (
										<div className="text-neutral-600 dark:text-neutral-400 break-words">사유: {r.reason}</div>
									)}
									{r.adminMemo && (
										<div className="text-neutral-500 mt-1">관리자: {r.adminMemo}</div>
									)}
									<div className="text-neutral-400 mt-1">요청 {getDateTime(r.requestedAt)}{r.resolvedAt && ` · 처리 ${getDateTime(r.resolvedAt)}`}</div>
								</div>
							))}
						</div>
					)}

					{/* 영수증 푸터 */}
					<div className="text-center text-xs text-neutral-400 mt-6 border-t border-dashed border-neutral-300 dark:border-neutral-700 pt-3">
						이용해 주셔서 감사합니다.
					</div>
				</div>

				{/* 액션 버튼 */}
				{!hasPending && (canCancel || canReturnExchange) && (
					<div className="mt-4 flex flex-wrap gap-2 justify-center">
						{canCancel && (
							<button
								type="button"
								onClick={() => openModal(1)}
								className="px-4 py-2 rounded border border-neutral-300 dark:border-neutral-700 text-sm hover:bg-neutral-50 dark:hover:bg-neutral-800"
							>
								주문 취소
							</button>
						)}
						{canReturnExchange && (
							<>
								<button
									type="button"
									onClick={() => openModal(2)}
									className="px-4 py-2 rounded border border-neutral-300 dark:border-neutral-700 text-sm hover:bg-neutral-50 dark:hover:bg-neutral-800"
								>
									반품 신청
								</button>
								<button
									type="button"
									onClick={() => openModal(3)}
									className="px-4 py-2 rounded border border-neutral-300 dark:border-neutral-700 text-sm hover:bg-neutral-50 dark:hover:bg-neutral-800"
								>
									교환 신청
								</button>
							</>
						)}
					</div>
				)}

				{hasPending && (
					<div className="mt-4 text-center text-xs text-amber-600">
						이미 처리 대기 중인 환불 요청이 있습니다. 관리자 검토 후 다시 신청하실 수 있습니다.
					</div>
				)}
			</div>

			{/* 환불 요청 모달 */}
			{refundOpen !== null && (
				<div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4" onClick={closeModal}>
					<div
						className="bg-white dark:bg-neutral-900 rounded-lg w-full max-w-md p-5"
						onClick={(e) => e.stopPropagation()}
					>
						<h2 className="text-lg font-bold mb-3">
							{REFUND_TYPE_LABEL[refundOpen]} 신청
						</h2>
						<p className="text-xs text-neutral-500 mb-4">
							{refundOpen === 1
								? '주문 취소를 신청합니다. 관리자 검토 후 처리되며, 결제 금액은 사용한 잔액 유형으로 환원됩니다.'
								: '신청 후 관리자 검토를 거쳐 처리됩니다. 배송 완료 후 30일 이내만 신청할 수 있습니다.'}
						</p>

						<label className="block text-xs font-semibold mb-1">사유 유형</label>
						<select
							value={reasonType}
							onChange={(e) => setReasonType(Number(e.target.value) as RefundReasonType)}
							className="w-full border border-neutral-300 dark:border-neutral-700 rounded px-3 py-2 text-sm mb-3 bg-white dark:bg-neutral-900"
						>
							{REASON_OPTIONS.map((opt) => (
								<option key={opt.value} value={opt.value}>{opt.label}</option>
							))}
						</select>

						<label className="block text-xs font-semibold mb-1">
							상세 사유 {reasonType === 7 && <span className="text-red-600">*</span>}
						</label>
						<textarea
							value={reasonMemo}
							onChange={(e) => setReasonMemo(e.target.value)}
							maxLength={500}
							rows={4}
							placeholder={reasonType === 7 ? '기타 사유를 입력해 주세요' : '추가 설명이 있다면 입력해 주세요 (선택)'}
							className="w-full border border-neutral-300 dark:border-neutral-700 rounded px-3 py-2 text-sm bg-white dark:bg-neutral-900 resize-none"
						/>
						<div className="text-[10px] text-neutral-400 text-right mt-0.5">{reasonMemo.length}/500</div>

						<div className="flex gap-2 mt-4 justify-end">
							<button
								type="button"
								onClick={closeModal}
								disabled={submitting}
								className="px-4 py-2 rounded border border-neutral-300 dark:border-neutral-700 text-sm hover:bg-neutral-50 dark:hover:bg-neutral-800"
							>
								취소
							</button>
							<button
								type="button"
								onClick={handleSubmit}
								disabled={submitting}
								className="px-4 py-2 rounded bg-blue-600 text-white text-sm hover:bg-blue-700 disabled:opacity-50"
							>
								{submitting ? '신청 중...' : '신청하기'}
							</button>
						</div>
					</div>
				</div>
			)}
		</>
	);
}
